<template>
  <div class="student">
    <el-card class="box-card">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="student-search">
        <el-input
        clearable
        placeholder="请输入学号"
        v-model="query"
        class="input-with-select"
        @clear="getStudentclear()"
        @input="getStudentlist()"
        >
        </el-input>
        <el-input
        placeholder="请输入届别"
        v-model="gradeData"
        style="width:150px"
        @keyup.native.enter="getStudentlist2()"
        >
          <i slot="suffix" class="el-input__icon el-icon-search search" @click="getStudentlist2()"></i>
        </el-input>
        <el-input
        placeholder="请输入专业班级"
        v-model="classData"
        style="width:150px"
        @keyup.native.enter="getStudentlist3()"
        >
          <i slot="suffix" class="el-input__icon el-icon-search search" @click="getStudentlist3()"></i>
        </el-input>
        <el-button type="success" class="student-btn" @click="addbtn()">添加学生</el-button>
        <el-button type="danger" @click="deletes()">删除已选</el-button>
        <el-button type="primary" @click="getStudentlist()">返回</el-button>
      </div>
      <div class="text item">
        <el-table
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        tooltip-effect="dark"
        :data='list'
        stripe
        style="width: 100%"
        height="470"
        v-loading="loading"
        >
          <el-table-column
          type="selection"
          width="55"
          >
          </el-table-column>
          <el-table-column
          prop="sid"
          label="学号"
          width="180"
          >
          </el-table-column>
          <el-table-column
          prop="sname"
          label="姓名"
          width="180"
          >
          </el-table-column>
          <el-table-column
          prop="major"
          label="专业"
          width="100"
          >
          </el-table-column>
          <el-table-column
          prop="cla"
          label="班级"
          width="180"
          >
          </el-table-column>
          <el-table-column
          prop="grade"
          label="届别"
          width="100"
          >
          </el-table-column>
          <el-table-column
          prop="editor"
          label="编辑"
          >
            <template slot-scope="scope">
              <el-button
              size="mini"
              plain
              type="primary"
              icon="el-icon-edit"
              circle
              @click="editor(scope.row)"
              >
              </el-button>
              <el-button
              size="mini"
              plain type="danger"
              icon="el-icon-delete"
              circle
              @click="deleteOpen(scope.row)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="Conpager" v-show="Conpage">
        <el-pagination
        class='stu-pager'
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNumber"
        :page-size="pageSize"
        :page-sizes="[8, 10]"
        layout="total,sizes, prev, pager, next, jumper"
        :total="totalCount"
        >
        </el-pagination>
      </div>
      <!-- 添加学生 -->
      <el-dialog title="添加学生" :visible.sync="dialogFormVisibleAdd" style="min-width: 1300px" @opened="ToFocus(1)">
          <el-tabs v-model="activeName" style="margin-top:-20px;height:400px" @tab-click="foc">
            <el-tab-pane label="批量添加" name="first" >
              <el-input
              placeholder="请输入专业班级"
              v-model="filename"
              style="width:300px"
              ref="one"
              >
              </el-input>
              <el-button
              class="down-demo"
              type="primary"
              @click="download"
              >
              下载模板
              </el-button>
              <el-upload
                class="upload-demo"
                ref="upload"
                :limit="1"
                accept=".xlsx,.xls"
                :action="uploadUrl()"
                :headers="headers"
                :before-upload="beforeup"
                :on-success="backinfo"
                :on-error="errorinfo"
                :file-list="fileList"
                :auto-upload="false"
                >
                <el-button
                slot="trigger"
                type="primary"
                style="margin-left: -10px;"
                >
                选取文件
                </el-button>
                <el-button
                style="margin-left: 10px;"
                type="success"
                @click="submitUpload"
                >
                上传到服务器
                </el-button>
                <div slot="tip" class="el-upload__tip">只能上传excel文件，文件名必须为：专业+班级，格式为：文件名.xlsx或文件名.xls</div>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="单个添加" name="second">
              <div class="singletab">
                <el-form :model="form">
                <el-form-item label="学号" :label-width="formLabelWidth">
                  <el-input v-model="form.sid" autocomplete="off" class="inputStyle" ref="two"></el-input>
                </el-form-item>
                <el-form-item label="姓名" :label-width="formLabelWidth">
                  <el-input v-model="form.sname" autocomplete="off" class="inputStyle"></el-input>
                </el-form-item>
                <el-form-item label="专业" :label-width="formLabelWidth">
                  <el-input v-model="form.major" autocomplete="off" class="inputStyle"></el-input>
                </el-form-item>
                <el-form-item label="班级" :label-width="formLabelWidth">
                  <!-- <el-select v-model="form.cla" placeholder="请选择班级"  style="width:360px">
                    <el-option v-for="item of classlist" :key="item.claId" :label="item.claName" :value="item.claName"></el-option>
                  </el-select> -->
                  <el-input v-model="form.cla" autocomplete="off" class="inputStyle"></el-input>
                </el-form-item>
                <el-form-item label="届别" :label-width="formLabelWidth">
                  <el-input v-model="form.grade" autocomplete="off" @keyup.native.enter="addform()" class="inputStyle"></el-input>
                </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button type="primary" @click="addform()">确 定</el-button>
                  <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
    </el-dialog>
    <!-- 编辑组件 -->
    <el-dialog title="编辑学生信息" :visible.sync="dialogEditorVisible" style="min-width: 1300px" @opened="ToFocus(2)">
      <el-form :model="form" style="text-align:left;margin-left:25%">
        <el-form-item label="学号" :label-width="formLabelWidth">
          <el-input disabled v-model="form.sid" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.sname" autocomplete="off" style="width:300px" @keyup.native="jump($event,15)" ref='five'></el-input>
        </el-form-item>
        <el-form-item label="专业" :label-width="formLabelWidth">
          <el-input v-model="form.major" autocomplete="off" style="width:300px" @keyup.native="jump($event,16)"></el-input>
        </el-form-item>
        <el-form-item label="班级" :label-width="formLabelWidth">
          <el-input v-model="form.cla" autocomplete="off" style="width:300px" @keyup.native="jump($event,17)"></el-input>
        </el-form-item>
        <el-form-item label="届别" :label-width="formLabelWidth">
          <el-input v-model="form.grade" autocomplete="off" style="width:300px" @keyup.native="jump($event,18)"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align:center">
        <el-button type="primary" @click="createdinfo()">确 定</el-button>
        <el-button @click="dialogEditorVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'student',
  data () {
    return {
      loading: false,
      Conpage: true,
      filename: '',
      // uploadUrl: `http://47.95.228.188:8081/auth/sys/student/batch?file=${this.file}`,
      multipleSelection: [],
      activeName: 'first',
      query: '',
      gradeData: '',
      classData: '',
      classlist: [],
      pageNumber: 1,
      pageSize: 8,
      totalCount: -1,
      list: [],
      dialogFormVisibleAdd: false,
      dialogEditorVisible: false,
      fileList: [],
      file: '',
      inputs: [],
      formLabelWidth: '40px',
      form: {
        sid: '',
        sname: '',
        major: '',
        cla: '',
        grade: ''
      }
    }
  },
  computed: {
    headers () {
      return {
        'token': sessionStorage.getItem('token')
      }
    }
  },
  mounted () {
    this.loading = true
  },
  created () {
    this.getStudentlist()
    this.getclasslist()
  },
  components: {},
  methods: {
    // 获取班级信息
    async getclasslist () {
      const res = await this.$http.get(`classes/list?pageNum=1&pageSize=9999&name=`)
      // console.log(res)
      const {code, msg, page} = res.data
      console.log(msg)
      // console.log(this.status)
      if (code === 200) {
        this.classlist = page.list
      } else {
        console.log(msg)
      }
    },
    // 按届别获取学生信息
    async getStudentlist2 () {
      const res = await this.$http.get(`student/list_grade/${this.gradeData}`)
      // console.log(res)
      const {code, msg, students} = res.data
      // console.log(this.status)
      if (code === 200) {
        this.list = students
        this.Conpage = false
      } else {
        console.log(msg)
      }
    },
    // 按专业班级获取学生信息
    async getStudentlist3 () {
      const res = await this.$http.get(`student/list_cla?cla=${this.classData}`)
      // console.log(res)
      const {code, msg, students} = res.data
      // console.log(this.status)
      if (code === 200) {
        this.list = students
        this.Conpage = false
      } else {
        console.log(msg)
      }
    },
    // 编辑学生信息
    editor (info) {
      this.form = info
      this.dialogEditorVisible = true
    },
    async createdinfo () {
      const res = await this.$http.put('student/update', this.form)
      // console.log(res)
      if (res.data.code === 200) {
        this.$message.success('修改成功！')
        this.dialogEditorVisible = false
        this.getStudentlist()
        this.form = {}
      } else {
        this.$message.error('error')
      }
    },
    // 删除学生信息
    deleteOpen (info) {
      this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const sid = info.sid
        const res = await this.$http.delete('student/delete', {data: {ids: [sid]}})
        const {msg, code} = res.data
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getStudentlist()
        } else {
          this.$message.error(msg)
        }
      }).catch(() => {})
    },
    // 批量删除
    deletes () {
      this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var ids = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].sid)
        }
        const res = await this.$http.delete('student/delete', {data: {ids: ids}})
        const {msg, code} = res.data
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getStudentlist()
        } else {
          this.$message.error(msg)
        }
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // })
      })
    },
    // 单个添加用户请求方法
    async addform () {
      const res = await this.$http.post('student/save', this.form)
      const {code, msg} = res.data
      // console.log(res)
      if (code === 200) {
        this.$message({
          type: 'success',
          message: '添加成功！'
        })
        this.getStudentlist()
        this.dialogFormVisibleAdd = false
        this.form = {}
      } else {
        this.$message.error(msg)
      }
    },
    // 添加按钮触发
    addbtn () {
      this.dialogFormVisibleAdd = true
      this.form = {}
      this.filename = ''
    },
    // 批量添加用户组件方法
    // 上传成功回调事件
    uploadUrl () {
      return `http://119.23.174.22:8080/auth/sys/student/batch`
      // return `http://39.9 8.227.154:8081/auth/sys/student/batch`
    },
    backinfo (response, file, fileList) {
      this.fileList = []
      console.log('上传成功', response)
      if (response.code === 200) {
        this.$message.success('上传成功！')
        this.getStudentlist()
      } else {
        this.$message.error(response.msg)
      }
    },
    // 上传失败回调事件
    errorinfo (response, file, fileList) {
      this.$message.error('上传失败，请重试！')
    },
    // 上传之前的验证
    beforeup (file) {
      // console.log(file)
      this.file = file.name
      // console.log('this.headers', this.headers)
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2) {
        this.$message.error('上传模板只能是 xls、xlsx格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传模板大小不能超过 10MB!')
      }
    },
    // 上传文件
    submitUpload () {
      let _this = this
      setTimeout(function () {
        _this.$refs.upload.submit()
      }, 200)
      setTimeout(function () {
        _this.dialogFormVisibleAdd = false
      }, 300)
    },
    // 下载文件
    async download () {
      if (this.filename === '') {
        this.filename = '学生上传的模板'
      }
      const AUTH_TOKEN = sessionStorage.getItem('token')
      this.$http.defaults.headers.common['token'] = AUTH_TOKEN
      const res = await this.$http.get(`student/excel/template/download`, {responseType: 'arraybuffer'})
      console.log(res)
      if (res.status === 200) {
        let url = window.URL.createObjectURL(new Blob([res.data], {type: 'application/vnd.ms-excel;charset=UTF-8'}))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', this.filename)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        this.$message.success('下载成功！')
      }
    },
    // 清空搜索框
    getStudentclear () {
      this.getStudentlist()
    },
    // 分页相关方法
    handleSizeChange (val) {
      this.pageSize = val
      // console.log(`每页 ${val} 条`)
      this.getStudentlist()
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      // console.log(`当前页: ${val}`)
      this.getStudentlist()
    },
    // 获取学生信息
    async getStudentlist () {
      this.Conpage = true
      // 需要授权的API必须设置请求头
      const AUTH_TOKEN = sessionStorage.getItem('token')
      this.$http.defaults.headers.common['token'] = AUTH_TOKEN
      // 后台token的key是token
      this.$http.defaults.headers.get['Content-Type'] = 'application/json'
      this.$http.defaults.headers.get['Accept'] = 'application/json'
      const res = await this.$http.get(`student/list?pageNum=${this.pageNumber}&pageSize=${this.pageSize}&sid=${this.query}`)
      const {code, msg, page} = res.data
      // console.log(res)
      if (code === 200) {
        this.list = page.list
        this.totalCount = page.totalCount
        this.loading = false
      } else {
        this.$message.error(msg)
        this.loading = false
      }
    },
    // 多选删除
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 获取焦点
    ToFocus (num) {
      if (num === 1) {
        this.$refs.one.focus()
        this.$refs.two.focus()
      }
      if (num === 2) {
        this.$refs.five.focus()
      }
    },
    foc (tab) {
      // console.log(tab.label)//
      let _this = this
      setTimeout(() => {
        if (tab.label === '批量添加') {
          _this.$refs.one.focus()
        }
        if (tab.label === '单个添加') {
          _this.$refs.two.focus()
        }
      }, 500)
    },
    // 按下按键时输入框的焦点转变
    jump (el, index) {
      this.inputs = document.getElementsByTagName('input')
      if (index === 15) {
        if (el.keyCode === 13 || el.keyCode === 39 || el.keyCode === 40) {
          this.inputs[index + 1].focus()
          this.inputs[index].blur()
        }
      } else if (index === 18) {
        if (el.keyCode === 37 || el.keyCode === 38) {
          // console.log(this.inputs[index - 1])
          this.inputs[index - 1].focus()
          this.inputs[index].blur()
        } else if (el.keyCode === 13) {
          this.createdinfo()
        }
      } else if (index > 15 && index < 18) {
        if (el.keyCode === 13 || el.keyCode === 39 || el.keyCode === 40) {
          // console.log(this.inputs[index + 1])
          this.inputs[index + 1].focus()
          this.inputs[index].blur()
        } else if (el.keyCode === 37 || el.keyCode === 38) {
          // console.log(this.inputs[index - 1])
          this.inputs[index - 1].focus()
          this.inputs[index].blur()
        }
      }
    }
  }
}
</script>

<style scoped lang="stylus">
.student,.box-card
  height 100%
  min-width: 1200px
  .student-search
    margin-top 15px
    width 100%
    .input-with-select
      width 300px
    .search
      cursor pointer
    .student-btn
      width 100px
  .text
    padding-top 10px
    height 470px
  .Conpager
    margin 0 auto
    padding-top 5px
  .stu-pager
    margin-top 54px
    text-align center
.dialog-footer
  text-align center
  margin-top 11%
  margin-left -35%
.upload-demo
  padding-left 10px
.down-demo
  margin 0 0 10px 0
.inputStyle
  width 300px
.singletab
  text-align left
  margin-left 25%
</style>
